package com.yuexi.anotation.aspect;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Field;

/**
 * 自动设置请求头中的值到参数中
 *
 * @author jie
 * @date 2022/9/26 -20:29
 */
@Aspect
@Component
public class AutoHeadAspect {

    @Pointcut("@annotation(com.yuexi.anotation.AutoHead)")
    public void pointcut() {
    }


    /**
     * 从请求头获取字段并设置到controller 请求参数中去，只支持对象作为入参
     */
    @Around("pointcut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        RequestAttributes ra = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes sra = (ServletRequestAttributes) ra;
        HttpServletRequest request = sra.getRequest();
        String userId = request.getHeader("userId");
        Object[] parameters = point.getArgs();
        if (null == parameters) {
            return point.proceed();
        }

        // 修改对象中的userId
        Object obj = parameters[0];
        Field field = obj.getClass().getDeclaredField("userId");
        field.setAccessible(true);
        field.set(obj, userId);
        return point.proceed();
    }

}
